package com.atwulidun.adapter05.springMVC;

import java.util.ArrayList;
import java.util.List;

public class DispatchServlet {
    // 存储各种适配器的List
    public static List<HandlerAdapter> handlerAdapters = new ArrayList<>();

    // 对存储各种适配器的List进行初始化
    public DispatchServlet() {
        handlerAdapters.add(new AnnotationHandlerAdapter());
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
    }

    // 根据controller获取对应的handlerAdapter，并通过handlerAdapter来调用controller的相应方法
    public void doDispatch() {
        // 此处模拟SpringMVC从request获取handler的对象，
        // 适配器可以获取到希望的Controller
//        HttpController controller = new HttpController();
//        AnnotationController controller = new AnnotationController();
        SimpleController controller = new SimpleController();
        // 得到对应的适配器
        HandlerAdapter adapter = getHandler(controller);
        // 再通过得到的适配器调用对应的controller的相应方法
        adapter.handle(controller);
    }

    private HandlerAdapter getHandler(Controller controller) {
        for (HandlerAdapter handlerAdapter : handlerAdapters) {
            if (handlerAdapter.supports(controller)) {
                return handlerAdapter;
            }
        }
        return null;
    }
}
